package com.ruoyi.system.controller;

import java.math.BigDecimal;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.mapper.OaPaySumMapper;
import com.ruoyi.system.mapper.OaProjectInitiationMapper;
import com.ruoyi.system.service.*;
import com.ruoyi.system.service.impl.OaPaySumServiceImpl;
import com.sun.org.apache.bcel.internal.generic.NEW;
import org.hibernate.validator.constraints.br.TituloEleitoral;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 记录采购实际付款Controller
 *
 * @author ruoyi
 * @date 2025-03-12
 */
@RestController
@RequestMapping("/system/purchase")
@Transactional
public class OaOtheraPurchaseController extends BaseController {
    @Autowired
    private IOaOtheraPurchaseService oaOtheraPurchaseService;
    @Autowired
    private IOaProjectInitiationService oaProjectInitiationService;
    @Autowired
    private IOaSupplierPayableSummaryService oaSupplierPayableSummaryService;
    @Autowired
    private IOaOtherService iOaOtherService;
    @Autowired
    private IOaPaySumService iOaPaySumService;
    @Autowired
    private IOaTicketSupplementService oaTicketSupplementService;
    @Autowired
    private OaPaySumMapper oaPaySumMapper;

    /**
     * 查询记录采购实际付款列表
     */
    @PreAuthorize("@ss.hasPermi('system:purchase:list')")
    @GetMapping("/list")
    public TableDataInfo list(OaOtheraPurchase oaOtheraPurchase) {
        startPage();
        List<OaOtheraPurchase> list = oaOtheraPurchaseService.selectOaOtheraPurchaseList(oaOtheraPurchase);
        return getDataTable(list);
    }

    /**
     * 导出记录采购实际付款列表
     */
    @PreAuthorize("@ss.hasPermi('system:purchase:export')")
    @Log(title = "记录采购实际付款", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, OaOtheraPurchase oaOtheraPurchase) {
        List<OaOtheraPurchase> list = oaOtheraPurchaseService.selectOaOtheraPurchaseList(oaOtheraPurchase);
        ExcelUtil<OaOtheraPurchase> util = new ExcelUtil<OaOtheraPurchase>(OaOtheraPurchase.class);
        util.exportExcel(response, list, "记录采购实际付款数据");
    }

    /**
     * 获取记录采购实际付款详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:purchase:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(oaOtheraPurchaseService.selectOaOtheraPurchaseById(id));
    }

    /**
     * 新增记录采购实际付款
     */
    @PreAuthorize("@ss.hasPermi('system:purchase:add')")
    @Log(title = "记录采购实际付款", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody OaOtheraPurchase oaOtheraPurchase) {
        // 检查传入的列表是否为空
        if (oaOtheraPurchase == null) {
            return AjaxResult.error("传入的采购列表为空");
        }
        // 判断是否增项
        OaOtheraPurchase isadd = isAdd(oaOtheraPurchase);
        oaOtheraPurchaseService.insertOaOtheraPurchase(isadd);
        return AjaxResult.success("新增记录采购实际付款成功");
    }

    /**
     * 判断是否为增项
     *
     * @param oaOtheraPurchase 待判断的对象
     * @return 判断后的对象
     */
    public OaOtheraPurchase isAdd(OaOtheraPurchase oaOtheraPurchase) {
        if (oaOtheraPurchase == null) {
            return null;
        }
//        if (oaOtheraPurchase.getType().equals("零星") || oaOtheraPurchase.getType().equals("其他")) {
            OaOtheraPurchase queryPurchase = new OaOtheraPurchase();
            queryPurchase.setInitiationId(oaOtheraPurchase.getInitiationId());
            queryPurchase.setOaOtherId(oaOtheraPurchase.getOaOtherId());
            List<OaOtheraPurchase> oaOtheraPurchases = oaOtheraPurchaseService.selectOaOtheraPurchaseList(queryPurchase);
            BigDecimal a = BigDecimal.ZERO;
            if (!oaOtheraPurchases.isEmpty()) {
                for (OaOtheraPurchase purchase : oaOtheraPurchases) {
                    a = a.add(purchase.getActualPrice());
                }
            }
            BigDecimal actualPrice = oaOtheraPurchase.getActualPrice().add(a);
            OaOther oaOther = iOaOtherService.selectOaOtherById(oaOtheraPurchase.getOaOtherId());
            System.out.println("actualPrice=" + actualPrice + "actualPrice1=" + oaOther.getTotalBudget());
            if (actualPrice.compareTo(oaOther.getTotalBudget()) > 0) {
                System.out.println("是");
                oaOtheraPurchase.setIsAdditionalItem(1);
            } else {
                System.out.println("否");
                oaOtheraPurchase.setIsAdditionalItem(0);
            }
            return oaOtheraPurchase;
//        } else {
//            // 查出所有白表数据
//            OaOtheraPurchase queryPurchase = new OaOtheraPurchase();
//            queryPurchase.setInitiationId(oaOtheraPurchase.getInitiationId());
//            queryPurchase.setPurchaseTableSequence(oaOtheraPurchase.getPurchaseTableSequence());
//            List<OaOtheraPurchase> oaOtheraPurchases = oaOtheraPurchaseService.selectOaOtheraPurchaseList2(queryPurchase);
//            // 获取粉表数据
//            OaOther queryOther = new OaOther();
//            queryOther.setInitiationId(oaOtheraPurchase.getInitiationId());
//            queryOther.setSupplier(oaOtheraPurchase.getPurchaseTableSequence());
//            List<OaOther> oaOthers = iOaOtherService.selectOaOtherList2(queryOther);
//            // 粉表 总 金额
//            BigDecimal totalPaymentAmount = calculateTotal(oaOthers, OaOther::getTotalBudget);
//            // 白表总金额
//            BigDecimal totalPaymentAmount1 = calculateTotal(oaOtheraPurchases, OaOtheraPurchase::getActualPrice);
//            BigDecimal totalPaymentAmount2 = totalPaymentAmount1.add(oaOtheraPurchase.getActualPrice());
//            System.out.println("==================");
//            System.out.println(totalPaymentAmount + "粉");
//            System.out.println(totalPaymentAmount2 + "白");
//            System.out.println("==================");
//            Long oaOtherId = oaOtheraPurchase.getOaOtherId();
//            OaOther oaOther = iOaOtherService.selectOaOtherById(oaOtherId);
//            BigDecimal totalBudget = oaOther.getTotalBudget();
//            BigDecimal actualPrice = oaOtheraPurchase.getActualPrice();
//            System.out.println(totalBudget + "粉");
//            System.out.println(actualPrice + "白");
//            System.out.println("==================");
//            // 如果白表金额大于粉表金额则为增项
//            //============================================
//            OaOtheraPurchase queryPurchase1 = new OaOtheraPurchase();
//            queryPurchase1.setInitiationId(oaOtheraPurchase.getInitiationId());
//            queryPurchase1.setOaOtherId(oaOtheraPurchase.getOaOtherId());
//            List<OaOtheraPurchase> oaOtheraPurchases1 = oaOtheraPurchaseService.selectOaOtheraPurchaseList(queryPurchase);
//            BigDecimal a = BigDecimal.ZERO;
//            if (!oaOtheraPurchases1.isEmpty()) {
//                for (OaOtheraPurchase purchase : oaOtheraPurchases1) {
//                    a = a.add(purchase.getActualPrice());
//                }
//            }
//            BigDecimal actualPrice1 = oaOtheraPurchase.getActualPrice().add(a);
//            //============================================
//            //            totalPaymentAmount2.compareTo(totalPaymentAmount) > 0 ||
//            if ( actualPrice1.compareTo(totalBudget) > 0) {
//                System.out.println("是");
//                oaOtheraPurchase.setIsAdditionalItem(1);
//            } else {
//                System.out.println("否");
//                oaOtheraPurchase.setIsAdditionalItem(0);
//            }
//
//            System.out.println("==================");
//            return oaOtheraPurchase;
//        }
    }

    /**
     * 计算列表中对象某个属性的总和
     *
     * @param list   列表
     * @param getter 属性获取方法引用
     * @param <T>    列表元素类型
     * @return 总和
     */
    private <T> BigDecimal calculateTotal(List<T> list, Function<T, BigDecimal> getter) {
        if (list == null || list.isEmpty()) {
            return BigDecimal.ZERO;
        }
        return list.stream()
                .map(getter)
                .filter(Objects::nonNull)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
    }

    /**
     * 修改记录采购实际付款
     */
    @PreAuthorize("@ss.hasPermi('system:purchase:edit')")
    @Log(title = "记录采购实际付款", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody OaOtheraPurchase oaOtheraPurchase) {
        OaOtheraPurchase oaOtheraPurchase1 = oaOtheraPurchaseService.selectOaOtheraPurchaseById(oaOtheraPurchase.getId());

        BigDecimal newInvoicePrice = oaOtheraPurchase.getInvoicePrice();
        BigDecimal oldInvoicePrice = oaOtheraPurchase1.getInvoicePrice();
        if (oaOtheraPurchase.getInvoiceStatus().equals("是")) {
            if (!oaOtheraPurchase1.getUploadedInvoice().equals(oaOtheraPurchase.getUploadedInvoice())) {
                //补票
                //获取应付汇总表的数据 减去之前的金额 再加上这次的新金额
                OaTicketSupplement oaTicketSupplement = new OaTicketSupplement();
                oaTicketSupplement.setSupplementId(oaOtheraPurchase.getId().toString());
                oaTicketSupplement.setIsCompleted(0);
                List<OaTicketSupplement> oaTicketSupplements = oaTicketSupplementService.selectOaTicketSupplementList(oaTicketSupplement);
                if (!oaTicketSupplements.isEmpty()) {
                    throw new RuntimeException("已有补票，请先审核。");
                }
                oaTicketSupplement.setOriginalAmount(oldInvoicePrice);
                oaTicketSupplement.setSupplementAmount(newInvoicePrice);
                oaTicketSupplement.setPath(oaOtheraPurchase1.getUploadedInvoice());
                oaTicketSupplementService.insertOaTicketSupplement(oaTicketSupplement);
                oaOtheraPurchase.setInvoiceReview("1");
                oaOtheraPurchase.setInvoicePrice(oaOtheraPurchase.getInvoicePrice());
            } else {
                if (newInvoicePrice.compareTo(oldInvoicePrice) != 0) {
                    throw new RuntimeException("禁止单独修改补课金额！如需调整金额，请通过修改发票信息完成");
                }
            }
        } else {
            System.out.println(" //没有开票");
            OaTicketSupplement oaTicketSupplement = new OaTicketSupplement();
            oaTicketSupplement.setSupplementId(oaOtheraPurchase.getId().toString());
            oaTicketSupplement.setIsCompleted(0);
            oaTicketSupplement.setOriginalAmount(oldInvoicePrice);
            oaTicketSupplement.setSupplementAmount(newInvoicePrice);
            oaTicketSupplement.setPath(oaOtheraPurchase1.getUploadedInvoice());
            oaTicketSupplementService.insertOaTicketSupplement(oaTicketSupplement);
            liuHaoApproval(oaOtheraPurchase.getId(), "通过");
            oaOtheraPurchase.setVerifiedAmount(oaOtheraPurchase.getVerifiedAmount().add(oaOtheraPurchase.getInvoicePrice()));
        }

        return toAjax(oaOtheraPurchaseService.updateOaOtheraPurchase(oaOtheraPurchase));
    }

    /**
     * 删除记录采购实际付款
     */
    @PreAuthorize("@ss.hasPermi('system:purchase:remove')")
    @Log(title = "记录采购实际付款", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        // 检查ID数组是否为空
        if (ids == null || ids.length == 0) {
            return error("请选择要删除的数据");
        }
        for (Long id : ids) {
            OaOtheraPurchase oaOtheraPurchase = oaOtheraPurchaseService.selectOaOtheraPurchaseById(id);
            if (oaOtheraPurchase.getIsAdditionalItem() == 1) {
                throw new RuntimeException("该记录为增项，禁止删除");
            }
            List<OaSupplierPayableSummary> oaSupplierPayableSummaries = oaSupplierPayableSummaryService.selectOaSupplierPayableSummaryList(new OaSupplierPayableSummary());
            if (!oaSupplierPayableSummaries.isEmpty()) {
                for (OaSupplierPayableSummary summary : oaSupplierPayableSummaries) {
                    for (String s : summary.getOtheraPurchaseId().split(",")) {
                        if (s.equals(id.toString())) {
                            OaPaySum oaPaySum = new OaPaySum();
                            oaPaySum.setPaybleSummaryId(summary.getId());
                            List<OaPaySum> oaPaySums = oaPaySumMapper.selectOaPaySumList(oaPaySum);
                            if (!oaPaySums.isEmpty()) {
                                throw new RuntimeException("该记录已付款，禁止删除");
                            }
                        }
                    }
                }
            }
        }
        try {
            List<OaSupplierPayableSummary> summaries = oaSupplierPayableSummaryService.selectOaSupplierPayableSummaryList(new OaSupplierPayableSummary());
            // 处理每个需要更新的记录
            for (OaSupplierPayableSummary summary : summaries) {
                for (String s : summary.getOtheraPurchaseId().split(",")) {
                    for (Long id : ids) {
                        if (s.equals(id.toString())) {
                                OaOtheraPurchase oaOtheraPurchase = oaOtheraPurchaseService.selectOaOtheraPurchaseById(id);
                            String otheraPurchaseId = summary.getOtheraPurchaseId();
                            String[] idSet = otheraPurchaseId.split(",");
                            StringBuilder stringBuilder = new StringBuilder();
                            for (String string : idSet) {
                                if (!string.equals(id.toString())) {
                                    stringBuilder.append(string).append(",");
                                }
                            }
                            if (stringBuilder.length() > 0) {
                                stringBuilder.deleteCharAt(stringBuilder.length() - 1);
                            }
                                summary.setOtheraPurchaseId(stringBuilder.toString());
                                BigDecimal subtract = summary.getQuotationAmount().subtract(oaOtheraPurchase.getActualPrice());
                                if (subtract.compareTo(BigDecimal.ZERO) == 0) {
                                    oaSupplierPayableSummaryService.deleteOaSupplierPayableSummaryById(summary.getId());
                                } else {
                                    summary.setQuotationAmount(summary.getQuotationAmount().subtract(oaOtheraPurchase.getActualPrice()));
                                    summary.setSettlementAmount(summary.getSettlementAmount().subtract(oaOtheraPurchase.getInvoicePrice()));
                                    oaSupplierPayableSummaryService.updateOaSupplierPayableSummary(summary);
                                }
                            }
                        }

                    }
                }

            // 删除主记录
            return toAjax(oaOtheraPurchaseService.deleteOaOtheraPurchaseByIds(ids));
        } catch (Exception e) {
            return error("删除失败：" + e.getMessage());
        }
    }

    @PutMapping("/edits")
    public AjaxResult edits(@RequestBody List<OaOtheraPurchase> oaOtheraPurchases) {
        for (OaOtheraPurchase other : oaOtheraPurchases) {
            oaOtheraPurchaseService.updateOaOtheraPurchase(other);
        }
        return AjaxResult.success("批量修改成功");
    }

    @PostMapping("/adds")
    public AjaxResult adds(@RequestBody List<OaOtheraPurchase> oaOtheraPurchases) {
        // 检查传入的列表是否为空
        if (oaOtheraPurchases == null || oaOtheraPurchases.isEmpty()) {
            return AjaxResult.error("传入的采购列表为空");
        }
        // 批量插入采购记录
        for (OaOtheraPurchase other : oaOtheraPurchases) {
            OaOtheraPurchase isadd = isAdd(other);
            oaOtheraPurchaseService.insertOaOtheraPurchase(isadd);
        }
        return AjaxResult.success("批量添加成功");
    }

    //生成应付汇总
    public void accountsPayableSummary1(OaOtheraPurchase purchase) {
        //判断同一立项有没有该供应商有则追加金额 没有则新增
        List<OaSupplierPayableSummary> list = Collections.emptyList();
        boolean a = false;
        OaProjectInitiation oaProjectInitiation = oaProjectInitiationService.selectOaProjectInitiationById(Integer.valueOf(purchase.getInitiationId()));
        if (purchase.getType().equals("供应商") || purchase.getType().equals("电商")) {
            OaSupplierPayableSummary oaSupplierPayableSummary = new OaSupplierPayableSummary();
            oaSupplierPayableSummary.setInitiationId(Long.valueOf(purchase.getInitiationId()));
            oaSupplierPayableSummary.setIsNumber(1L);
            oaSupplierPayableSummary.setSupplierName(purchase.getPurchaseTableSequence());
            list = oaSupplierPayableSummaryService.selectOaSupplierPayableSummaryByIdAndSupplier(oaSupplierPayableSummary);
        } else {
            //其他和零星采购拉过来
            a = true;
        }
        if (a) {
            //添加生成条件  1 增项的都审核完成 2 发票审核完成  遍历其他采购列表
            if (purchase.getInvoiceReview().equals("1") || purchase.getInvoiceReview().equals("3") ||
                    purchase.getLiApprove().equals("1") || purchase.getLiApprove().equals("3") ||
                    purchase.getLiuApprove().equals("1") || purchase.getLiuApprove().equals("3") ||
                    purchase.getPrincipalApprove().equals("1") || purchase.getPrincipalApprove().equals("3")
            ) {
                System.out.println(1);
            } else {
                System.out.println(2);
                //创建OaSupplierPayableSummary对象
                OaSupplierPayableSummary oaSupplierPayableSummary = new OaSupplierPayableSummary();
                //设置供应商名称
                oaSupplierPayableSummary.setSupplierName(purchase.getPurchaseTableSequence());
                //设置项目编号
                oaSupplierPayableSummary.setProjectNumber(oaProjectInitiation.getProjectNumber());
                //设置项目名称
                oaSupplierPayableSummary.setProjectName(oaProjectInitiation.getProjectContent());
                //设置报价金额
                oaSupplierPayableSummary.setQuotationAmount(purchase.getActualPrice());
                //设置结算金额
                oaSupplierPayableSummary.setSettlementAmount(purchase.getInvoicePrice());
                //设置负责人
                oaSupplierPayableSummary.setPersonInCharge(oaProjectInitiation.getInitiationPersonInCharge());
                //设置开始日期
                oaSupplierPayableSummary.setStartDate(oaProjectInitiation.getCommencementDate());
                //设置完成日期
                oaSupplierPayableSummary.setCompletionDate(oaSupplierPayableSummary.getCompletionDate());
                //判断项目是否完成
                if (oaProjectInitiation.getComplete() == 1) {
                    //设置项目完成状态为已完结
                    oaSupplierPayableSummary.setIsProjectCompleted("已完结");
                } else {
                    //设置项目完成状态为未完结
                    oaSupplierPayableSummary.setIsProjectCompleted("未完结");
                }
                oaSupplierPayableSummary.setIsNumber(2L);
                //设置发起id
                oaSupplierPayableSummary.setInitiationId(Long.valueOf(oaProjectInitiation.getId()));
                oaSupplierPayableSummary.setIsAmountSettled("未结清");
                oaSupplierPayableSummary.setOtheraPurchaseId(purchase.getId().toString());
                //插入应付汇总
                oaSupplierPayableSummaryService.insertOaSupplierPayableSummary(oaSupplierPayableSummary);
            }
            return;
        }

        if (list.isEmpty()) {
            //添加生成条件  1 增项的都审核完成 2 发票审核完成  遍历其他采购列表
            if (purchase.getInvoiceReview().equals("1") || purchase.getInvoiceReview().equals("3") ||
                    purchase.getLiApprove().equals("1") || purchase.getLiApprove().equals("3") ||
                    purchase.getLiuApprove().equals("1") || purchase.getLiuApprove().equals("3") ||
                    purchase.getPrincipalApprove().equals("1") || purchase.getPrincipalApprove().equals("3")
            ) {
                System.out.println(3);
            } else {
                System.out.println(4);
                //创建OaSupplierPayableSummary对象
                OaSupplierPayableSummary oaSupplierPayableSummary = new OaSupplierPayableSummary();
                //设置供应商名称
                oaSupplierPayableSummary.setSupplierName(purchase.getPurchaseTableSequence());
                //设置项目编号
                oaSupplierPayableSummary.setProjectNumber(oaProjectInitiation.getProjectNumber());
                //设置项目名称
                oaSupplierPayableSummary.setProjectName(oaProjectInitiation.getProjectContent());
                //设置报价金额
                oaSupplierPayableSummary.setQuotationAmount(purchase.getActualPrice());
                //设置结算金额
                oaSupplierPayableSummary.setSettlementAmount(purchase.getInvoicePrice());
                //设置负责人
                oaSupplierPayableSummary.setPersonInCharge(oaProjectInitiation.getInitiationPersonInCharge());
                //设置开始日期
                oaSupplierPayableSummary.setStartDate(oaProjectInitiation.getCommencementDate());
                //设置完成日期
                oaSupplierPayableSummary.setCompletionDate(oaSupplierPayableSummary.getCompletionDate());
                //判断项目是否完成
                if (oaProjectInitiation.getComplete() == 1) {
                    //设置项目完成状态为已完结
                    oaSupplierPayableSummary.setIsProjectCompleted("已完结");
                } else {
                    //设置项目完成状态为未完结
                    oaSupplierPayableSummary.setIsProjectCompleted("未完结");
                }
                //设置是否编号
                oaSupplierPayableSummary.setIsNumber(1L);
                //设置发起id
                oaSupplierPayableSummary.setInitiationId(Long.valueOf(oaProjectInitiation.getId()));
                oaSupplierPayableSummary.setIsAmountSettled("未结清");
                oaSupplierPayableSummary.setOtheraPurchaseId(purchase.getId().toString());
                //插入应付汇总
                oaSupplierPayableSummaryService.insertOaSupplierPayableSummary(oaSupplierPayableSummary);
            }
        } else {
            if (purchase.getInvoiceReview().equals("1") || purchase.getInvoiceReview().equals("3") ||
                    purchase.getLiApprove().equals("1") || purchase.getLiApprove().equals("3") ||
                    purchase.getLiuApprove().equals("1") || purchase.getLiuApprove().equals("3") ||
                    purchase.getPrincipalApprove().equals("1") || purchase.getPrincipalApprove().equals("3")
            ) {
                System.out.println("55");
            } else {
                System.out.println("66");
                OaSupplierPayableSummary oaSupplierPayableSummary = list.get(0);
                oaSupplierPayableSummary.setQuotationAmount(oaSupplierPayableSummary.getQuotationAmount().add(purchase.getActualPrice()));
                oaSupplierPayableSummary.setSettlementAmount(oaSupplierPayableSummary.getSettlementAmount().add(purchase.getInvoicePrice()));
                String originalIds = oaSupplierPayableSummary.getOtheraPurchaseId();
                String combinedIds = (originalIds != null ? originalIds + "," : "") + purchase.getId();
                // 使用HashSet去重
                Set<String> uniqueIds = new HashSet<>(Arrays.asList(combinedIds.split(",")));
                // 过滤掉空字符串（如果存在）并重新拼接
                String newIds = String.join(",", uniqueIds.stream()
                        .filter(id -> !id.isEmpty())
                        .collect(Collectors.toList()));
                // 设置回对象
                oaSupplierPayableSummary.setOtheraPurchaseId(newIds);
                oaSupplierPayableSummaryService.updateOaSupplierPayableSummary(oaSupplierPayableSummary);
            }
        }
    }

    /**
     * 白表增项时负责人审批方法
     *
     * @return 审批结果，true 表示通过，false 表示不通过
     */
    @GetMapping("/principalApproval")
    public AjaxResult principalApproval(Long id, String msg) {
        OaOtheraPurchase oaOtheraPurchase = oaOtheraPurchaseService.selectOaOtheraPurchaseById(id);
        if (msg.equals("通过")) {
            oaOtheraPurchase.setPrincipalApprove("2");
            oaOtheraPurchaseService.updateOaOtheraPurchase(oaOtheraPurchase);
            return success("审核通过");
        } else {
//            oaOtheraPurchase.setPrincipalApprove("3");
//            oaOtheraPurchaseService.updateOaOtheraPurchase(oaOtheraPurchase);
            oaOtheraPurchaseService.deleteOaOtheraPurchaseById(id);
            return error("审核不通过");
        }
    }

    //负责人审核列表
    @GetMapping("/princip")
    public AjaxResult princip() {
        OaOtheraPurchase oaOtheraPurchase = new OaOtheraPurchase();
        oaOtheraPurchase.setPrincipalApprove("1");
        oaOtheraPurchase.setLiApprove("1");
        oaOtheraPurchase.setLiuApprove("1");
        List<OaOtheraPurchase> oaOtheraPurchases = oaOtheraPurchaseService.selectOaOtheraPurchaseList(oaOtheraPurchase);
        HashSet<String> strings = new HashSet<>();
        for (OaOtheraPurchase purchase : oaOtheraPurchases) {
            strings.add(purchase.getInitiationId());
        }
        ArrayList<OaProjectInitiation> oaProjectInitiations = new ArrayList<>();
        for (String s : strings) {
            OaProjectInitiation oaProjectInitiation = oaProjectInitiationService.selectOaProjectInitiationById(Integer.valueOf(s));
            oaProjectInitiations.add(oaProjectInitiation);
        }

        return success(oaProjectInitiations);
    }

    //李琨审核列表
    @GetMapping("/liKun")
    public AjaxResult liKun() {
        OaOtheraPurchase oaOtheraPurchase = new OaOtheraPurchase();
        oaOtheraPurchase.setLiApprove("1");
        oaOtheraPurchase.setPrincipalApprove("2");
        oaOtheraPurchase.setLiuApprove("1");
        List<OaOtheraPurchase> oaOtheraPurchases = oaOtheraPurchaseService.selectOaOtheraPurchaseList(oaOtheraPurchase);
        HashSet<String> strings = new HashSet<>();
        for (OaOtheraPurchase purchase : oaOtheraPurchases) {
            strings.add(purchase.getInitiationId());
        }
        ArrayList<OaProjectInitiation> oaProjectInitiations = new ArrayList<>();
        for (String s : strings) {
            OaProjectInitiation oaProjectInitiation = oaProjectInitiationService.selectOaProjectInitiationById(Integer.valueOf(s));
            oaProjectInitiations.add(oaProjectInitiation);
        }

        return success(oaProjectInitiations);
    }

    //刘昕审核列表
    @GetMapping("/liuXin")
    public AjaxResult liuXin() {
        OaOtheraPurchase oaOtheraPurchase = new OaOtheraPurchase();
        oaOtheraPurchase.setPrincipalApprove("2");
        oaOtheraPurchase.setLiuApprove("1");
        oaOtheraPurchase.setLiApprove("2");
        List<OaOtheraPurchase> oaOtheraPurchases = oaOtheraPurchaseService.selectOaOtheraPurchaseList(oaOtheraPurchase);
        HashSet<String> strings = new HashSet<>();
        for (OaOtheraPurchase purchase : oaOtheraPurchases) {
            strings.add(purchase.getInitiationId());
        }
        ArrayList<OaProjectInitiation> oaProjectInitiations = new ArrayList<>();
        for (String s : strings) {
            OaProjectInitiation oaProjectInitiation = oaProjectInitiationService.selectOaProjectInitiationById(Integer.valueOf(s));
            oaProjectInitiations.add(oaProjectInitiation);
        }

        return success(oaProjectInitiations);
    }

    /**
     * 白表增项时李琨审批方法
     *
     * @return 审批结果，true 表示通过，false 表示不通过
     */
    @GetMapping("/liKunApproval")
    public AjaxResult liKunApproval(Long id, String msg) {
        OaOtheraPurchase oaOtheraPurchase = oaOtheraPurchaseService.selectOaOtheraPurchaseById(id);
        if (msg.equals("通过")) {
            oaOtheraPurchase.setLiApprove("2");
            oaOtheraPurchaseService.updateOaOtheraPurchase(oaOtheraPurchase);
            return success("审核通过");
        } else {
//            oaOtheraPurchase.setLiApprove("3");
//            oaOtheraPurchaseService.updateOaOtheraPurchase(oaOtheraPurchase);
            oaOtheraPurchaseService.deleteOaOtheraPurchaseById(id);
            return error("审核不通过");

        }
    }

    /**
     * 白表增项时刘昕审批方法
     *
     * @return 审批结果，true 表示通过，false 表示不通过
     */
    @GetMapping("/liuXinApproval")
    public AjaxResult liuXinApproval(Long id, String msg) {
        OaOtheraPurchase oaOtheraPurchase = oaOtheraPurchaseService.selectOaOtheraPurchaseById(id);
        if (msg.equals("通过")) {
            oaOtheraPurchase.setLiuApprove("2");
            oaOtheraPurchaseService.updateOaOtheraPurchase(oaOtheraPurchase);
            accountsPayableSummary1(oaOtheraPurchase);
            return success("审核通过");
        } else {
//            oaOtheraPurchase.setLiuApprove("3");
            oaOtheraPurchaseService.deleteOaOtheraPurchaseById(id);
//            oaOtheraPurchaseService.updateOaOtheraPurchase(oaOtheraPurchase);
            return error("审核不通过");
        }
    }

    //吕昊发票审核数据列表
    @GetMapping("/liuHao")
    public AjaxResult liuHao() {
        OaOtheraPurchase oaOtheraPurchase = new OaOtheraPurchase();
        oaOtheraPurchase.setInvoiceReview("1");
        List<OaOtheraPurchase> oaOtheraPurchases = oaOtheraPurchaseService.selectOaOtheraPurchaseList(oaOtheraPurchase);
        HashSet<String> strings = new HashSet<>();
        for (OaOtheraPurchase purchase : oaOtheraPurchases) {
            strings.add(purchase.getInitiationId());
        }
        ArrayList<OaProjectInitiation> oaProjectInitiations = new ArrayList<>();
        for (String s : strings) {
            OaProjectInitiation oaProjectInitiation = oaProjectInitiationService.selectOaProjectInitiationById(Integer.valueOf(s));
            oaProjectInitiations.add(oaProjectInitiation);
        }
        return success(oaProjectInitiations);
    }

    //吕昊发票审核按钮
    @GetMapping("/liuHaoApproval")
    public AjaxResult liuHaoApproval(Long id, String msg) {
        OaOtheraPurchase oaOtheraPurchase = oaOtheraPurchaseService.selectOaOtheraPurchaseById(id);
        if (msg.equals("通过")) {
            oaOtheraPurchase.setInvoiceReview("2");
            oaOtheraPurchase.setInvoiceReviewdate(new Date());
            //设置已审金额
            oaOtheraPurchase.setVerifiedAmount(oaOtheraPurchase.getVerifiedAmount().add(oaOtheraPurchase.getInvoicePrice()));
            oaOtheraPurchaseService.updateOaOtheraPurchase(oaOtheraPurchase);
            //补票
            OaTicketSupplement oaTicketSupplement = new OaTicketSupplement();
            oaTicketSupplement.setSupplementId(oaOtheraPurchase.getId().toString());
            oaTicketSupplement.setIsCompleted(0);
            List<OaTicketSupplement> oaTicketSupplements = oaTicketSupplementService.selectOaTicketSupplementList(oaTicketSupplement);
            if (!oaTicketSupplements.isEmpty()) {
                System.out.println("补票===============================");
                List<OaSupplierPayableSummary> oaSupplierPayableSummaries = oaSupplierPayableSummaryService.selectOaSupplierPayableSummaryList(new OaSupplierPayableSummary());
                for (OaSupplierPayableSummary summary : oaSupplierPayableSummaries) {
                    for (String s : summary.getOtheraPurchaseId().split(",")) {
                        if (s.equals(oaOtheraPurchase.getId().toString())) {
                            summary.setSettlementAmount(summary.getSettlementAmount().add(oaTicketSupplements.get(0).getSupplementAmount()));
                            oaSupplierPayableSummaryService.updateOaSupplierPayableSummary(summary);
                            oaTicketSupplements.get(0).setIsCompleted(1);
                            oaTicketSupplementService.updateOaTicketSupplement(oaTicketSupplements.get(0));
                        }
                    }
                }
            } else {
                System.out.println("新增===============================");
                accountsPayableSummary1(oaOtheraPurchase);
            }
            return success("审核通过");
        } else {
            //新增
            oaOtheraPurchase.setInvoiceReview("3");
            oaOtheraPurchase.setInvoiceReviewdate(new Date());
            OaTicketSupplement oaTicketSupplement = new OaTicketSupplement();
            oaTicketSupplement.setSupplementId(oaOtheraPurchase.getId().toString());
            oaTicketSupplement.setIsCompleted(0);
            List<OaTicketSupplement> oaTicketSupplements = oaTicketSupplementService.selectOaTicketSupplementList(oaTicketSupplement);
            oaOtheraPurchaseService.updateOaOtheraPurchase(oaOtheraPurchase);
            if (!oaTicketSupplements.isEmpty()) {
                //补票
                oaTicketSupplements.get(0).setIsCompleted(1);
                oaOtheraPurchase.setUploadedInvoice(oaTicketSupplements.get(0).getPath());
                oaOtheraPurchaseService.updateOaOtheraPurchase(oaOtheraPurchase);
                oaTicketSupplementService.updateOaTicketSupplement(oaTicketSupplements.get(0));
            } else {
                oaOtheraPurchaseService.deleteOaOtheraPurchaseById(oaOtheraPurchase.getId());
            }
            return error("审核不通过");
        }
    }

    @GetMapping("/payableSummary")
    public AjaxResult PayableSummary() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        // 查询所有的 OaOtheraPurchase 记录
        List<OaOtheraPurchase> oaOtheraPurchases = oaOtheraPurchaseService.selectOaOtheraPurchaseList(new OaOtheraPurchase());
        // 存储最终结果的列表
        List<ProjectInfo> projectInfos = new ArrayList<>();

        // 提前查询所有的 OaSupplierPayableSummary 记录，避免在循环中重复查询
        List<OaSupplierPayableSummary> oaSupplierPayableSummaries = oaSupplierPayableSummaryService.selectOaSupplierPayableSummaryList(new OaSupplierPayableSummary());
        // 构建一个映射，键为 otheraPurchaseId，值为对应的 OaSupplierPayableSummary 列表
        Map<String, List<OaSupplierPayableSummary>> purchaseIdToSummariesMap = new HashMap<>();
        for (OaSupplierPayableSummary summary : oaSupplierPayableSummaries) {
            String[] split = summary.getOtheraPurchaseId().split(",");
            for (String s : split) {
                purchaseIdToSummariesMap.computeIfAbsent(s, k -> new ArrayList<>()).add(summary);
            }
        }

        for (OaOtheraPurchase purchase : oaOtheraPurchases) {
            // 根据 purchase 的 initiationId 查询对应的 OaProjectInitiation 记录
            OaProjectInitiation oaProjectInitiation = oaProjectInitiationService.selectOaProjectInitiationById(Integer.valueOf(purchase.getInitiationId()));
            // 创建一个新的 ProjectInfo 对象
            ProjectInfo projectInfo = new ProjectInfo();
            projectInfo.setId(purchase.getId());
            // 设置项目编号
            projectInfo.setProjectId(oaProjectInitiation.getProjectNumber());
            // 设置项目内容
            projectInfo.setProjectName(oaProjectInitiation.getProjectContent());
            // 设置供应商名称
            projectInfo.setSupplierName(purchase.getPurchaseTableSequence());
            // 设置项目开始日期
            projectInfo.setEstablishmentDate(oaProjectInitiation.getCommencementDate());
            // 设置发起 ID
            projectInfo.setInitiationId(oaProjectInitiation.getId());

            // 计算总金额
            BigDecimal totalAmount = BigDecimal.ZERO;
            List<Long> relatedSummaryIds = new ArrayList<>();
            List<OaSupplierPayableSummary> relatedSummaries = purchaseIdToSummariesMap.getOrDefault(purchase.getId().toString(), Collections.emptyList());
            for (OaSupplierPayableSummary summary : relatedSummaries) {
                totalAmount = totalAmount.add(summary.getQuotationAmount());
                relatedSummaryIds.add(summary.getId());
            }
            projectInfo.setTotalAmount(totalAmount);

            // 计算已支付金额
            BigDecimal paidAmount = BigDecimal.ZERO;
            for (Long summaryId : relatedSummaryIds) {
                OaPaySum oaPaySum = new OaPaySum();
                oaPaySum.setPaybleSummaryId(summaryId);
                List<OaPaySum> oaPaySums = iOaPaySumService.selectOaPaySumList(oaPaySum);
                for (OaPaySum sum : oaPaySums) {
                    paidAmount = paidAmount.add(sum.getPaymentAmount());
                }
            }
            projectInfo.setPaidAmount(paidAmount);
            projectInfo.setEstablishmentDate1(oaProjectInitiation.getCompleteDate());
            projectInfo.setProjectLeader(oaProjectInitiation.getInitiationPersonInCharge());
            Integer complete = oaProjectInitiation.getComplete();
            if (complete != null) {
                projectInfo.setIsProjectCompleted("未完结");
            } else if (complete == 1) {
                projectInfo.setIsProjectCompleted("已完结");
            } else {
                projectInfo.setIsProjectCompleted("未完结");
            }
            projectInfo.setWhiteListOperator(purchase.getFiller());
            ArrayList<OaSupplierPayableSummary> oaSupplierPayableSummaries2 = new ArrayList<>();
            List<OaSupplierPayableSummary> oaSupplierPayableSummaries1 = oaSupplierPayableSummaryService.selectOaSupplierPayableSummaryList(new OaSupplierPayableSummary());
            for (OaSupplierPayableSummary summary : oaSupplierPayableSummaries1) {
                String[] split = summary.getOtheraPurchaseId().split(",");
                for (String s : split) {
                    if (s.equals(purchase.getId().toString())) {
                        oaSupplierPayableSummaries2.add(summary);
                    }
                }

            }
            if (oaSupplierPayableSummaries2.size() > 1) {
                throw new RuntimeException("存在多条记录");
            }
            if (!oaSupplierPayableSummaries2.isEmpty()) {
                projectInfo.setProjectRemark(oaSupplierPayableSummaries2.get(0).getRemark());
                projectInfo.setOaSupplierPayableSummary(oaSupplierPayableSummaries2.get(0));
                Long isNumber = oaSupplierPayableSummaries2.get(0).getIsNumber();
                if (isNumber == 1L) {
                    projectInfo.setIsnumber("供应商");
                } else {
                    projectInfo.setIsnumber("报销");
                }
                if (isNumber == 2L) {
                    //其他零星
                    projectInfo.setIsnumber1("0");
                } else {
                    //供应商电商
                    projectInfo.setIsnumber1("1");
                }
                projectInfo.setInvoiceAmount(oaSupplierPayableSummaries2.get(0).getSettlementAmount());
            }
            // 将处理好的 ProjectInfo 对象添加到结果列表中
            projectInfos.add(projectInfo);
        }
        List<ProjectInfo> deduplicatedList = null;
        if (loginUser.getUsername().equals("李婧荧")) {
            deduplicatedList = projectInfos;
        } else {
            deduplicatedList = deduplicateProjectInfos(projectInfos);
        }
        // 返回成功结果
        return AjaxResult.success(deduplicatedList);
    }

    public static List<ProjectInfo> deduplicateProjectInfos(List<ProjectInfo> projectInfos) {
        Map<String, ProjectInfo> uniqueMap = new HashMap<>();
        for (ProjectInfo info : projectInfos) {
            String key = info.getInitiationId() + "_" + info.getSupplierName() + "_" + info.getIsnumber();
            uniqueMap.putIfAbsent(key, info);
        }
        return new ArrayList<>(uniqueMap.values());
    }
}
